package com.hcinfos.gsoo.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.params.HttpParams;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.MenuDetailAdapter;
import com.hcinfos.gsoo.adapter.WaimaiListAdapter;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Constants;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.GdMealsDish;
import com.hcinfos.gsoo.enity.GdSupplerBasicConf;
import com.hcinfos.gsoo.enity.GdTakeAwayBasicConf;
import com.hcinfos.gsoo.enity.GdTakeAwayOrder;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.enity.ViewSuppSearchExt;
import com.hcinfos.gsoo.enity.WDoMenuDetailEnity;
import com.hcinfos.gsoo.enity.WDoSumbitEnity;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.json.UserJson;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.LoginUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.CommonDataKinds.Relation;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 外卖订单确认页面
 * 
 * @author xi
 * 
 */
public class WaimaiOrderConfirActivity extends Activity implements
		OnClickListener {

	private ImageView back_iv;
	private ListView listView;
	private MenuDetailAdapter adapter;
	private List<GdMealsDish> list;
	private TextView order_tv;

	private TextView num_tv;
	private TextView price_tv;
	private EditText ticket_et;
	private ObjectMapper objectMapper;

	public final int DO_ORDER_SUCCESS = 0x2200;
	public final int DO_ORDER_FAIL = DO_ORDER_SUCCESS + 1;
	public final int LOGIN = DO_ORDER_SUCCESS + 2;
	public final int UPDATE_SUCCESS = DO_ORDER_SUCCESS + 3;
	public final int UPDATE_FAIL = DO_ORDER_SUCCESS + 4;
	public final int ADD_LOGIN = DO_ORDER_SUCCESS + 5;
	public final int LOGIN_SUCCESS = UPDATE_SUCCESS + 6;
	public final int LOGIN_FAIL = UPDATE_SUCCESS + 7;
	private Dialog dialog;
	private Context context;
	private RadioGroup piao_rg;
	private RelativeLayout piao_rl;
	private RelativeLayout isNeed_piao_rl;
	private TextView online_pay_tv;
	private TextView arrive_pay_tv;
	private SharePreferenceUtil util;
	private GdSupplerBasicConf conf;
	private boolean isOnlinePay = true;
	private User user;
	private TextView name_tv;
	private TextView tel_tv;
	private TextView address_tv;
	private ImageView add_address_iv;
	private RelativeLayout address_rl;
	private double servicePrice = 0.0;// 外卖 订桌费用

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		util = new SharePreferenceUtil(this, "setting");
		setContentView(R.layout.activity_waimaiorderconfir);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;

		address_rl = (RelativeLayout) findViewById(R.id.address_rl);
		add_address_iv = (ImageView) findViewById(R.id.add_address_iv);
		add_address_iv.setOnClickListener(this);
		name_tv = (TextView) findViewById(R.id.name_tv);
		tel_tv = (TextView) findViewById(R.id.tel_tv);
		address_tv = (TextView) findViewById(R.id.address_tv);
		online_pay_tv = (TextView) findViewById(R.id.online_pay_tv);
		online_pay_tv.setOnClickListener(this);
		arrive_pay_tv = (TextView) findViewById(R.id.arrive_pay_tv);
		arrive_pay_tv.setOnClickListener(this);
		arrive_pay_tv.setVisibility(View.GONE);
		isNeed_piao_rl = (RelativeLayout) findViewById(R.id.isNeed_piao_rl);
		piao_rl = (RelativeLayout) findViewById(R.id.piao_rl);
		piao_rg = (RadioGroup) findViewById(R.id.piao_rg);
		dialog = DialogUtil.createProgressDialog(this, "订单提示", "订单提交中...");
		context = this;
		objectMapper = new ObjectMapper();
		ticket_et = (EditText) findViewById(R.id.ticket_et);
		num_tv = (TextView) findViewById(R.id.num_tv);
		price_tv = (TextView) findViewById(R.id.price_tv);

		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.listView);
		order_tv = (TextView) findViewById(R.id.order_tv);
		order_tv.setOnClickListener(this);

		list = new ArrayList<GdMealsDish>();
		adapter = new MenuDetailAdapter(this, list);
		listView.setAdapter(adapter);

		piao_rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int radioButtonId = group.getCheckedRadioButtonId();
				switch (radioButtonId) {
				case R.id.need_rb:
					piao_rl.setVisibility(View.VISIBLE);
					break;
				case R.id.unneed_rb:
					piao_rl.setVisibility(View.GONE);
					break;
				}
			}
		});
		conf = (GdSupplerBasicConf) getIntent().getSerializableExtra(
				"detailExt");
		servicePrice = getIntent().getDoubleExtra("price", 0.0);
		if (conf != null) {
			if (conf.getSupportOnlinePay() == 0) {
				online_pay_tv.setVisibility(View.GONE);
			} else {
				online_pay_tv.setVisibility(View.VISIBLE);
			}
			if (conf.getSupprotInvoice() == 0) {
				isNeed_piao_rl.setVisibility(View.GONE);
				piao_rl.setVisibility(View.GONE);
			} else {
				isNeed_piao_rl.setVisibility(View.VISIBLE);
				piao_rl.setVisibility(View.VISIBLE);

			}
		} else {
			return;
		}
	}

	private void refreshData() {
		list.clear();
		int totalNum = 0;
		double totalPrice = 0.0;
		double price = 0.0;
		Map<String, GdMealsDish> orderMap = GsooApplication.menuMap;
		for (String key : orderMap.keySet()) {
			GdMealsDish extend = orderMap.get(key);
			totalNum += extend.getNum();
			price = extend.getDishPrice() * extend.getNum();
			totalPrice += price;
			list.add(extend);
		}
		num_tv.setText(totalNum + "");
		price_tv.setText("¥" + (totalPrice + servicePrice));
		adapter.setDataChange(list);
	}

	@Override
	protected void onResume() {
		refreshData();
		user = (User) util.loadObject("user");
		if (user != null && user.getSendAddr1() != null) {
			name_tv.setText("收货人:" + user.getTaName());
			tel_tv.setText(user.getTaTelphone());
			address_tv.setText(user.getSendAddr1());
			address_rl.setVisibility(View.VISIBLE);
			add_address_iv.setVisibility(View.GONE);
		} else {
			address_rl.setVisibility(View.GONE);
			add_address_iv.setVisibility(View.VISIBLE);
		}

		super.onResume();
	}

	private String orderId;

	/**
	 * 提交订单信息
	 */
	private void doSumbitOrder() {
		HttpUtils httpUtils = UtilHttp.getHttpUtils(this);

		RequestParams params = new RequestParams();
		LogUtil.d("wxf", "params=" + getParams());
		params.addBodyParameter("order", getParams());
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.W_GET_SUBMIT, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf", arg0.toString());
						handler.sendEmptyMessage(DO_ORDER_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> text) {
						LogUtil.d("wxf", "orderInfo = " + text.result);
						try {
							JSONObject obj = new JSONObject(text.result);
							String message = obj.getString("message");
							int state = obj.getInt("state");
							if (state == 200) {
								orderId = obj.getJSONObject("data").getString(
										"id");
								handler.sendEmptyMessage(DO_ORDER_SUCCESS);
							} else if (state == 198) {
								handler.sendEmptyMessage(LOGIN);
							} else {
								Message msg = handler.obtainMessage();
								msg.what = DO_ORDER_FAIL;
								msg.obj = message;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(DO_ORDER_FAIL);

						}
					}
				});
	}

	private String getParams() {

		List<WDoMenuDetailEnity> list = new ArrayList<WDoMenuDetailEnity>();
		Map<String, GdMealsDish> orderMap = GsooApplication.menuMap;
		for (String key : orderMap.keySet()) {
			GdMealsDish extend = orderMap.get(key);
			WDoMenuDetailEnity enity = new WDoMenuDetailEnity();
			enity.setDishId(extend.getId());
			enity.setNum(extend.getNum());
			list.add(enity);
		}

		WDoSumbitEnity enity = new WDoSumbitEnity();
		if (piao_rl.getVisibility() == View.GONE) {
			enity.setInvoiceState(0);
			enity.setInvoiceTitle("");
		} else {
			enity.setInvoiceState(1);
			enity.setInvoiceTitle(ticket_et.getText().toString() + "");
		}

		enity.setPayState("1");
		enity.setUserTelphone(user.getTaTelphone());
		enity.setUserTaName(user.getTaName());
		enity.setOrderDetails(list);
		enity.setArrivedAddr(user.getSendAddr1());
		enity.setSuppId(conf.getId());
		enity.setOrderType("1");
		enity.setContactName(user.getTaName());
		enity.setSuppNick(conf.getSuppName());

		try {
			String result = objectMapper.writeValueAsString(enity);
			return result;
		} catch (Exception e) {

			return null;
		}

	}

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.back_iv:
			finish();
			break;
		case R.id.order_tv:
			// intent = new Intent(this, WaimaiOrderDetailActivity.class);
			// startActivity(intent);
			if (user == null) {
				Toast.makeText(this, "请先登陆再操作!", 500).show();
				Intent intent = new Intent(this, LoginActivity.class);
				intent.putExtra("type", Constants.LOGIN_CODE);
				startActivityForResult(intent, 0);
				return;
			}
			if (piao_rl.getVisibility() == View.VISIBLE
					&& ticket_et.getText().toString().length() == 0) {
				Toast.makeText(this, "请输入发票信息title", 500).show();
				return;
			} else if (user.getSendAddr1() == null) {
				Toast.makeText(this, "请添加外卖地址相关信息!", 500).show();
				return;
			}
			dialog.show();
			doSumbitOrder();
			break;
		case R.id.add_address_iv:
			if (user == null) {
				Toast.makeText(this, "请先登陆再操作!", 500).show();
				Intent intent = new Intent(this, LoginActivity.class);
				intent.putExtra("type", Constants.LOGIN_CODE);
				startActivityForResult(intent, 0);
				return;
			} else {
				Intent intent = new Intent(this, AddressUpdateActivity.class);
				startActivity(intent);
			}
			break;

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		user = (User) util.loadObject("user");
	};

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case DO_ORDER_FAIL:
				dialog.dismiss();
				String errorMsg = "订单提交失败";
				if (msg.obj != null)
					errorMsg = msg.obj.toString();
				Toast.makeText(context, errorMsg, 500).show();
				break;
			case DO_ORDER_SUCCESS:
				dialog.dismiss();
				GsooApplication.menuMap.clear();
				intent = new Intent(WaimaiOrderConfirActivity.this,
						WaimaiOrderDetailActivity.class);
				intent.putExtra("orderId", orderId);
				startActivity(intent);
				finish();
				break;
			case LOGIN:
				LoginUtil.isLoginSuccess(WaimaiOrderConfirActivity.this,
						handler);
				break;
			case LoginUtil.LOGIN_FAIL:
				dialog.dismiss();
				Toast.makeText(WaimaiOrderConfirActivity.this, "提交失败!", 500)
						.show();
				break;
			case LoginUtil.LOGIN_SUCCESS:
				LogUtil.d("wxf", "SUCCESS");
				doSumbitOrder();
				break;

			}
		};
	};

}
